/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.service.settlement;

import com.server.common.persistence.Page;
import com.server.common.security.RSASignUtils;
import com.server.common.service.CrudService;
import com.server.modules.sys.dao.settlement.SettlementDao;
import com.server.modules.sys.entity.settlement.Settlement;
import com.server.modules.sys.entity.settlement.item.SettlementItem;
import com.server.modules.sys.service.settlement.item.SettlementItemService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 结算总表Service
 * @author 丁光彪
 * @version 2016-11-21
 */
@Service
@Transactional(readOnly = true)
public class SettlementService extends CrudService<SettlementDao, Settlement> {
@Resource
private SettlementItemService settlementItemService;
	public Settlement get(String id) {
		return super.get(id);
	}
	
	public List<Settlement> findList(Settlement settlement) {
		return super.findList(settlement);
	}
	
	public Page<Settlement> findPage(Page<Settlement> page, Settlement settlement) {
		return super.findPage(page, settlement);
	}
	
	@Transactional(readOnly = false)
	public void save(Settlement settlement) {
		super.save(settlement);
	}
	
	@Transactional(readOnly = false)
	public void delete(Settlement settlement) {
		super.delete(settlement);
	}

	/**
	 * 级联保存结算记录（包括结算明细，如果没有结算明细 不进行保存）
	 * @param settlement
	 * @return
	 */
	@Transactional(readOnly = false)
    public boolean saveCascade(Settlement settlement) throws Exception {
		if(settlement==null|| CollectionUtils.isEmpty(settlement.getItems())){
			return false;
		}
		this.save(settlement);
        List<SettlementItem> items = settlement.getItems();
        for (SettlementItem item : items) {
			item.setSettlementId(settlement.getId());
			//签名
			item.setSignature(RSASignUtils.sign((item.getAmount()+item.getSettlementId()).getBytes(),RSASignUtils.getKeyByKeyFileName("privateKey.keystore")));
            settlementItemService.save(item);
        }
        return true;
    }
}